﻿<%@ WebHandler Language="C#" Class="Training.Web.AjaxHandler.Transaction.PelatihanDetailHandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using Training.Library.DataAccess.Administration;
using Training.Library.DomainObject.Administration;

using Training.Library.DataAccess.Transaction;
using Training.Library.DomainObject.Transaction;

using Training.Library.Enum;
using Training.Web.Support;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Web.SessionState;
using Training.Library.DataAccess.Administration.Catalog;
using Training.Library.DomainObject.Administration.Catalog;

using SIPO.Library.DataAccess.Administration.Catalog;
using SIPO.Library.DomainObject.Administration.Catalog;
namespace Training.Web.AjaxHandler.Transaction
{

    public class PelatihanDetailHandler : Training.Web.BaseHandler, IRequiresSessionState
    {
        private  PelatihanDetailRepo PelatihanDetailDal = new PelatihanDetailRepo(ConfigurationManager.ConnectionStrings["TrainingConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["TrainingConn"].ConnectionString);
        private string MethodName = string.Empty;
        private static List<int> listPeserta = new List<int>();

        private BagianRepo BagianDal = new BagianRepo(ConfigurationManager.ConnectionStrings["TrainingConn"].ConnectionString);
        private KaryawanRepo KaryawanDal = new KaryawanRepo(ConfigurationManager.ConnectionStrings["TrainingConn"].ConnectionString);
        
        private DepartmentRepo DepartmentDal = new DepartmentRepo(ConfigurationManager.ConnectionStrings["JobdescConn"].ConnectionString);
        private PositionRepo PositionDal = new PositionRepo(ConfigurationManager.ConnectionStrings["JobdescConn"].ConnectionString);

        private CabangRepo CabangDal = new CabangRepo(ConfigurationManager.ConnectionStrings["TrainingConn"].ConnectionString);
        private LokasiRepo LokasiDal = new LokasiRepo(ConfigurationManager.ConnectionStrings["TrainingConn"].ConnectionString);

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);
            MethodName = context.Request.Params["method"];
            context.Response.Clear();
            context.Response.Buffer = true;

            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);
            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            sr.Close();
            sr.Dispose();

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context, jObj));
                    break;
                case ("update"):
                    context.Response.Write(Update(context, jObj));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context, jObj));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;

                case ("getdatasubgrid"):
                    context.Response.Write(GetDataSubGrid(context));
                    break;
                    
                case ("settosession"):
                    context.Response.Write(this.SetToSession(context, jObj));
                    break;

                case ("clearsession"):
                    context.Session.Remove("PelatihanDetail");
                    //context.Session.Remove("sInitialize_s_t_wop_detail");
                    break;

                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();
        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string SetToSession(HttpContext context,JObject jo)
        {
            JSONHelper helper = new JSONHelper();
            try
            {

                List<PelatihanDetail> listPelatihanDetail = context.Session["PelatihanDetail"] as List<PelatihanDetail>;
                if (listPelatihanDetail == null)
                {
                    listPelatihanDetail = new List<PelatihanDetail>();
                    context.Session["PelatihanDetail"] = listPelatihanDetail;
                }
               // else
                //{
                var query = listPelatihanDetail.Where(x => x.NIK == (string)jo["NIK"]);

                    if (query.ToList().Count > 0)
                    {
                        helper.Message = "Data tidak berhasil di simpan,peserta tersebut sudah pernah di input !";
                        helper.IsSuccess = true;
                    }
                    else
                    {
                        PelatihanDetail obj = new PelatihanDetail();
                        obj.NIK = (string)jo["NIK"];
                        obj.CreatedBy = base.UserLoggedIn;
                        obj.CreatedDate = DateTime.Now;

                        listPelatihanDetail.Add(obj);

                        helper.Message = "Data berhasil di simpan !";
                        helper.IsSuccess = true;

                    }
               // }

                
               
            }
            catch(Exception ex)
            {
                helper.Message = ex.Message;
                helper.IsSuccess = false;
            }

            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Set Session";
                log.LogMessage = helper.Message;
                log.LogSource = "PelatihanDetailhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }
            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);
        }

        private string Insert(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                listPeserta.Add((int)jo["PesertaID"]);
                
                //PelatihanDetail obj = new PelatihanDetail();
                //obj.PelatihanID = (int)jo["PelatihanID"];
                //obj.PesertaID = (int)jo["PesertaID"];
                //obj.CreatedDate = DateTime.Now;
                //obj.CreatedBy = base.UserLoggedIn;

                //PelatihanDetailDal.Save(obj);

                helper.Message = "Data berhasil di simpan !";
                helper.IsSuccess = true;

            }
            catch (Exception ex)
            {

                helper.Message = ex.Message;
                helper.IsSuccess = false;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "PelatihanDetailhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Update(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                PelatihanDetail obj = new PelatihanDetail();
                obj.DetailID = (int)jo["PelatihanDetailID"];
                obj.PelatihanID = (int)jo["PelatihanID"];
                obj.NIK = (string)jo["NIK"];
                
                obj.UpdatedDate = DateTime.Now;
                obj.UpdatedBy = base.UserLoggedIn;

                PelatihanDetailDal.Update(obj);
                helper.Message = "Data berhasil di ubah !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update";
                log.LogMessage = helper.Message;
                log.LogSource = "PelatihanDetailhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Delete(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var strId = (string)jo["ID"];
                List<PelatihanDetail> listPelatihanDetail = context.Session["PelatihanDetail"] as List<PelatihanDetail>;
                string[] ids = strId.Split(',');
                foreach (string id in ids)
                {
                    int intID = Convert.ToInt32(id);
                    //PelatihanDetailDal.Delete(intID);

                    var obj = listPelatihanDetail.Where(x => x.NIK == (id));
                    
                    foreach(PelatihanDetail data in obj.ToList())
                    {
                        listPelatihanDetail.Remove(data);
                    }

                    
                }

                context.Session["PelatihanDetail"] = listPelatihanDetail;
                helper.IsSuccess = true;
                helper.Message = "Data berhasil di hapus !";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Delete";
                log.LogMessage = helper.Message;
                log.LogSource = "PelatihanDetailhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

      

        private string GetData(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? PelatihanDetail.Fields.DetailID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            //DataTable dt = new DataTable();
            //dt.Columns.Add("PesertaID");

            int totalCount = 0;
            int totalPages = 0;
            List<PelatihanDetail> pagedList = null;


                parameters = " WHERE PelatihanID=" + context.Request.Params["PelatihanID"];
                
               

                //List<Bagian> listBagian = BagianDal.GetList();
                List<Cabang> listCabang = CabangDal.GetList();
                List<Lokasi> listLokasi = LokasiDal.GetList();
                List<Karyawan> listKaryawan = KaryawanDal.GetList();
                List<Position> listJabatan = PositionDal.GetList();
                List<Department> listDepartemen = DepartmentDal.GetList();
            
                
               pagedList = PelatihanDetailDal.GetList(pageSize, page, sidx, sord, parameters);

               if (context.Session["PelatihanDetail"] == null)
                   context.Session["PelatihanDetail"] = pagedList;
               else
                   pagedList = context.Session["PelatihanDetail"] as List<PelatihanDetail>;

               totalCount = pagedList.Count;// Convert.ToInt32(PelatihanDetailDal.SelectScalar(SQL.Function.Aggregate.Count, PelatihanDetail.Fields.DetailID, parameters));

               decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
               totalPages = Convert.ToInt32(dc);


                var rows = from p in pagedList  join karyawan in listKaryawan on p.NIK equals karyawan.NIK 
                           join cabang in listCabang on karyawan.CabangID equals cabang.CabangID
                           join lokasi in listLokasi on karyawan.LokasiID equals lokasi.LokasiID
                           join jabatan in listJabatan on karyawan.PositionID equals jabatan.PositionID
                           join dept in listDepartemen on jabatan.DepartmentID equals dept.DeptID 
                           select new
                           {

                               NIK = karyawan.NIK,
                               NamaKaryawan = karyawan.NamaKaryawan,
                               Jabatan = jabatan.PositionName,
                               Cabang = cabang.NamaCabang,
                               Lokasi = lokasi.NamaLokasi,
                               Departemen = dept.DepartmentDesc
                           };



                if (sord.ToLower().Equals("asc"))
                {
                    if (sidx.Contains("NamaKaryawan"))
                        rows = rows.OrderBy(x => x.NamaKaryawan);
                    if (sidx.Contains("NIK"))
                        rows = rows.OrderBy(x => x.NIK);
                    if (sidx.Contains("Department"))
                        rows = rows.OrderBy(x => x.Departemen);
                    if (sidx.Contains("Cabang"))
                        rows = rows.OrderBy(x => x.Cabang);
                    if (sidx.Contains("Lokasi"))
                        rows = rows.OrderBy(x => x.Lokasi);
                    if (sidx.Contains("PositionName"))
                        rows = rows.OrderBy(x => x.Jabatan);
                    
                    
                }
                else
                {
                    if (sidx.Contains("NamaKaryawan"))
                        rows = rows.OrderByDescending(x => x.NamaKaryawan);
                    if (sidx.Contains("NIK"))
                        rows = rows.OrderByDescending(x => x.NIK);
                    if (sidx.Contains("Departmen"))
                        rows = rows.OrderByDescending(x => x.Departemen);
                    if (sidx.Contains("Cabang"))
                        rows = rows.OrderBy(x => x.Cabang);
                    if (sidx.Contains("Lokasi"))
                        rows = rows.OrderBy(x => x.Lokasi);
                    if (sidx.Contains("PositionName"))
                        rows = rows.OrderByDescending(x => x.Jabatan);
                }
            
                // send params into jqGrid's format
                var gridData = new
                {
                    page = page,
                    total = totalPages,
                    records = totalCount,
                    rows = rows,
                };

                return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
          
          

        }


        private string GetDataSubGrid(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context);

            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? PelatihanDetail.Fields.DetailID : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            //DataTable dt = new DataTable();
            //dt.Columns.Add("PesertaID");

            int totalCountDetail = 0;
            int totalPagesDetail = 0;
            List<PelatihanDetail> pagedList = null;


            parameters = " WHERE PelatihanID=" + context.Request.Params["PelatihanID"];



            //List<Bagian> listBagian = BagianDal.GetList();
            List<Cabang> listCabang = CabangDal.GetList();
            List<Lokasi> listLokasi = LokasiDal.GetList();
            List<Karyawan> listKaryawan = KaryawanDal.GetList();
            List<Position> listJabatan = PositionDal.GetList();
            List<Department> listDepartemen = DepartmentDal.GetList();


            pagedList = PelatihanDetailDal.GetList(pageSize, page, sidx, sord, parameters);

            //if (context.Session["PelatihanDetail"] == null)
            //    context.Session["PelatihanDetail"] = pagedList;
            //else
            //    pagedList = context.Session["PelatihanDetail"] as List<PelatihanDetail>;

            totalCountDetail = Convert.ToInt32(PelatihanDetailDal.SelectScalar(SQL.Function.Aggregate.Count, PelatihanDetail.Fields.DetailID, parameters));

            decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCountDetail) / Convert.ToDecimal(pageSize));
            totalPagesDetail = Convert.ToInt32(dc);

            var rows = from p in pagedList
                       join karyawan in listKaryawan on p.NIK equals karyawan.NIK
                       join cabang in listCabang on karyawan.CabangID equals cabang.CabangID
                       join lokasi in listLokasi on karyawan.LokasiID equals lokasi.LokasiID
                       join jabatan in listJabatan on karyawan.PositionID equals jabatan.PositionID
                       join dept in listDepartemen on jabatan.DepartmentID equals dept.DeptID
                       select new
                       {

                           NIK = karyawan.NIK,
                           NamaKaryawan = karyawan.NamaKaryawan,
                           Jabatan = jabatan.PositionName,
                           Cabang = cabang.NamaCabang,
                           Lokasi = lokasi.NamaLokasi,
                           Departemen = dept.DepartmentDesc
                       };



            if (sord.ToLower().Equals("asc"))
            {
                if (sidx.Contains("NamaKayawan"))
                    rows = rows.OrderBy(x => x.NamaKaryawan);
                if (sidx.Contains("NIK"))
                    rows = rows.OrderBy(x => x.NIK);
                if (sidx.Contains("Departmen"))
                    rows = rows.OrderBy(x => x.Departemen);
                if (sidx.Contains("Cabang"))
                    rows = rows.OrderBy(x => x.Cabang);
                if (sidx.Contains("Lokasi"))
                    rows = rows.OrderBy(x => x.Lokasi);
                if (sidx.Contains("PositionName"))
                    rows = rows.OrderBy(x => x.Jabatan);


            }
            else
            {
                if (sidx.Contains("NamaKaryawan"))
                    rows = rows.OrderByDescending(x => x.NamaKaryawan);
                if (sidx.Contains("NIK"))
                    rows = rows.OrderByDescending(x => x.NIK);
                if (sidx.Contains("Departmen"))
                    rows = rows.OrderByDescending(x => x.Departemen);
                if (sidx.Contains("Cabang"))
                    rows = rows.OrderBy(x => x.Cabang);
                if (sidx.Contains("Lokasi"))
                    rows = rows.OrderBy(x => x.Lokasi);
                if (sidx.Contains("PositionName"))
                    rows = rows.OrderByDescending(x => x.Jabatan);
            }

            // send params into jqGrid's format
            var gridDataDetail = new
            {
                page = page,
                total = totalPagesDetail,
                records = totalCountDetail,
                rows = rows,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridDataDetail);



        }

    }

}